package tv.huan.web.controller.media;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tv.huan.common.annotation.Log;
import tv.huan.common.core.controller.BaseController;
import tv.huan.common.core.domain.AjaxResult;
import tv.huan.common.core.page.TableDataInfo;
import tv.huan.common.enums.BusinessType;
import tv.huan.common.utils.StringUtils;
import tv.huan.common.utils.http.HttpUtils;
import tv.huan.framework.util.ShiroUtils;
import tv.huan.media.domain.TencentInfo;
import tv.huan.media.service.ITencentInfoService;
import tv.huan.system.domain.SysUser;

/**
 * 配置信息Controller
 *
 * @author admin
 * @date 2019-09-03
 */
@Controller
@RequestMapping("/media/tencentInfo")
public class TencentInfoController extends BaseController
{
    @Value("${tencent.url}")
    private String tencentUrl;

    @Value("${tencent.appkey}")
    private String appkey;

    @Value("${tencent.appid}")
    private String appid;

    @Value("${tencent.version}")
    private String version;

    @Value("${huan.pcClientApi}")
    private String pcClientApi;

    private String prefix = "media";

    @Autowired
    private ITencentInfoService tencentInfoService;

    private static final Logger log = LoggerFactory.getLogger(TencentInfoController.class);

    @RequiresPermissions("media:tencentInfo:view")
    @GetMapping()
    public String tencentInfo()
    {
        return prefix + "/tencentInfo";
    }

    /**
     * 查询配置信息列表
     */
    @RequiresPermissions("media:tencentInfo:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TencentInfo tencentInfo)
    {
        startPage();
        List<TencentInfo> list = tencentInfoService.selectTencentInfoList(tencentInfo);
        return getDataTable(list);
    }

    /**
     * 修改配置信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        TencentInfo tencentInfo = tencentInfoService.selectTencentInfoById(id);
        mmap.put("tencentInfo", tencentInfo);
        return prefix + "/tencentInfoEdit";
    }

    /**
     * 修改保存配置信息
     */
    @RequiresPermissions("media:tencentInfo:edit")
    @Log(title = "内容审核", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TencentInfo tencentInfo)
    {
        return toAjax(tencentInfoService.updateTencentInfo(tencentInfo));
    }

    /**
     * Android获取腾讯视频账号密码接口
     */
    @PostMapping("/getTencentInfo")
    @ResponseBody
    public String getTencentInfo(String userId)
    {
        JSONObject jsonObject = new JSONObject();
        List<TencentInfo> list = tencentInfoService.selectTencentInfoList(null);
        String exitUserId;
        TencentInfo tencentInfo = null;
        for (TencentInfo t : list){
            exitUserId = t.getUserId();
            if (StringUtils.isNotEmpty(exitUserId)){
                if (exitUserId.contains(userId)){
                    tencentInfo = t;
                    break;
                }else {
                    int count = exitUserId.indexOf(",");
                    if (count < 0){
                        t.setUserId(exitUserId + "," + userId);
                        tencentInfoService.updateTencentInfo(t);
                        tencentInfo = t;
                        break;
                    }
                }
            }else {
                t.setUserId(userId);
                tencentInfoService.updateTencentInfo(t);
                tencentInfo = t;
                break;
            }
        }

        if (null != tencentInfo){
            jsonObject.put("tencentUser",tencentInfo.getTencentUser());
            jsonObject.put("vuid",tencentInfo.getVuid());
            jsonObject.put("vtoken",tencentInfo.getVtoken());
        }else {
            jsonObject.put("tencentUser","szgxhuanwang0010");
            jsonObject.put("vuid","1829701698");
            jsonObject.put("vtoken","402549D0B7A12739C17A551069B9C9D9");
        }
        return  jsonObject.toJSONString();
    }

    /**
     * 获取token
     */
    @PostMapping("/getToken")
    @ResponseBody
    public String getToken(String userId){
        JSONObject json = new JSONObject();
        json.put("status","success");
        json.put("code",200);
        String url = tencentUrl + "get_token?format=json&version=" + version + "&appid=" + appid + "&appkey=" + appkey;
        log.info("url:" + url);
        JSONObject resObj = getJsonObj(url);
        log.info("获取apkInfo：" + resObj.toString());
        if (resObj != null && resObj.getJSONObject("result").getIntValue("code") == 0){
            JSONObject data = resObj.getJSONObject("data");
            if (null != data){
                json.put("data",data);
            }
    }
        return json.toJSONString();
    }

    private JSONObject getJsonObj(String url){
        JSONObject object;
        String jsonTemp = getJson(url);
        if(null == jsonTemp || jsonTemp.equals("error")){
            return null;
        }
        try {
            object = JSONObject.parseObject(jsonTemp);
        } catch (JSONException e) {
            log.error("字符串无法转换为JSONObject，json数据请求url：{}，返回结果：{}",url,jsonTemp);
            return null;
        }
        return object;
    }


	/**
     * 根据传入url获取json数据
	 * param httpURLString
	 * return jsonString
	 * */
    private String getJson(String str){
        return getText(str,"utf-8");
    }

    private String getText(String str,String encode){
        log.info("getText_url: "+str);
        StringBuffer json = new StringBuffer();
        HttpURLConnection conn = null;
        try {
            URL url = new URL(str);
            conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),encode));
            String temp;
            while((temp = br.readLine())!=null){
                json.append(temp);
            }
            br.close();
        } catch (ConnectException e) {
            log.error("联网获取数据出错,url:"+str);
            e.printStackTrace();
            return "error";
        }catch(IOException e){
            log.error("联网I/O出错");
            e.printStackTrace();
            return "error";
        }finally{
            conn.disconnect();
        }
        return json.toString();
    }

    /**
     * PC播放时调用接口传当前用户以及播放地址
     */
    @PostMapping("/sendUserInfo")
    @ResponseBody
    public AjaxResult sendUserInfo(String url){
        JSONObject json = new JSONObject();
        //当前用户
        SysUser user = ShiroUtils.getSysUser();
        json.put("id",user.getLoginName());
        json.put("ftpurl",url);
        String result = HttpUtils.postWithJson(pcClientApi,json.toString());
        logger.info("PC播放传参结果::::{}",result);
        return AjaxResult.success("调用播放成功");
    }

}